<template>
  <grid :title="id === 'add' ? '新建项目' : '编辑项目'">
    <el-form ref="form"
             style="text-align: left; width:1000px"
             label-width="100px"
             @submit.native.prevent="onFormSubmit"
             :model="form"
             :rules="rules">
      <el-form-item label="标题"
                    prop="title">
        <el-input v-model="form.title"
                  placeholder="请输入标题，限30个字"
                  clearable></el-input>
      </el-form-item>
      <el-form-item label="简介"
                    prop="summary">
        <el-input v-model="form.summary"
                  type="textarea"
                  placeholder="请输入简介，限200个字"
                  clearable></el-input>
      </el-form-item>
      <el-form-item label="仓库地址"
                    prop="github">
        <el-input v-model="form.github"
                  placeholder="请输入仓库地址"
                  clearable></el-input>
      </el-form-item>
      <el-form-item label="封面图"
                    prop="image">
        <image-input type="project"
                     v-model="form.image"></image-input>
        <p class="caption">注：建议上传尺寸60*60的 PNG图</p>
      </el-form-item>
      <el-form-item label="关键词"
                    prop="keywords">
        <el-tag v-for="(tag,index) in form.keywords"
                :key="index"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)">
          {{tag}}
        </el-tag>
        <template v-if="inputVisible">
          <el-input class="input-new-tag"
                    v-model="inputValue"
                    ref="saveTagInput"
                    size="small"
                    @blur="handleInputConfirm">
          </el-input>
        </template>
        <template v-else>
          <el-button class="button-new-tag"
                     size="small"
                     @click="showInput">+ New</el-button>
        </template>
      </el-form-item>
      <el-form-item label="项目时间"
                    prop="time">
        <el-date-picker v-model="form.start_time"
                        type="date"
                        placeholder="选择开始日期"
                        format="yyyy 年 MM 月 dd 日"
                        value-format="timestamp">
        </el-date-picker>
        -
        <el-date-picker v-model="form.end_time"
                        type="date"
                        placeholder="选择结束日期"
                        format="yyyy 年 MM 月 dd 日"
                        value-format="timestamp">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="显示">
        <el-checkbox v-model="form.status"
                     :true-label="1"
                     :false-label="0">开启</el-checkbox>
        <p class="caption">关闭后项目将不可见</p>
      </el-form-item>
      <el-form-item label="项目类型">
        <el-radio-group v-model="form.type">
          <el-radio :label="1">网站</el-radio>
          <el-radio :label="2">小程序</el-radio>
          <el-radio :label="3">App</el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="isWebsite">
        <el-form-item label="网站地址"
                      prop="code">
          <el-input v-model="form.website"
                    placeholder="请输入项目部署地址"
                    clearable></el-input>
        </el-form-item>
      </template>
      <template v-if="isApplets">
        <el-form-item label="小程序码"
                      prop="code">
          <image-input type="project"
                       v-model="form.code"></image-input>
          <p class="caption">注：建议上传尺寸60*60的 PNG图</p>
        </el-form-item>
      </template>
      <template v-if="isApplication">
        <el-form-item label="下载地址"
                      prop="code">
          <image-input type="project"
                       v-model="form.code"></image-input>
          <p class="caption">注：将下载地址转换为二维码然后上传</p>
        </el-form-item>
      </template>
      <el-form-item label="内容"
                    prop="content">
        <markdown-editor v-model="form.content">
        </markdown-editor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   native-type="submit">保存</el-button>
        <router-link :to="{ name: 'project'}">
          <el-button>取消</el-button>
        </router-link>
      </el-form-item>
    </el-form>
  </grid>
</template>

<script>
import imageInput from '@/components/image-input'
import markdownEditor from '@/components/mark-down-editor'
import { store, edit, fetchView } from './api'

export default {
  title () {
    return this.id === 'add' ? '新增项目' : '编辑项目'
  },
  props: {
    id: {
      type: String,
      default: 'add'
    }
  },
  data () {
    const validateCode = (rule, value, callback) => {
      if (this.isWebsite && (value === '' || value === undefined)) {
        callback(new Error('请输入项目部署地址'))
      } else if (this.isApplets && value.length === 0) {
        callback(new Error('请上传小程序码'))
      } else if (this.isApplication && value.length === 0) {
        callback(new Error('请上传下载地址'))
      } else {
        callback()
      }
    }
    return {
      inputVisible: false,
      inputValue: '',
      form: {},
      formDefault: {
        title: undefined,
        summary: undefined,
        github: undefined,
        type: 1,
        keywords: [],
        image: [],
        code: [],
        content: undefined,
        website: undefined,
        start_time: '',
        end_time: '',
        status: 1
      },
      rules: {
        title: [
          { required: true, message: '标题不能为空' },
          { max: 30, message: '最长30个字' }
        ],
        summary: [
          { max: 200, message: '最长200个字' }
        ],
        content: [
          { required: true, message: '内容不能为空' }
        ],
        code: [
          { validator: validateCode }
        ]
      }
    }
  },
  components: {
    imageInput, markdownEditor
  },
  async mounted () {
    if (this.id !== 'add') {
      const {
        data: { data }
      } = await fetchView(this.id)
      this.form = await this.filterTopic(data)
    } else {
      this.form = this.formDefault
    }
  },
  computed: {
    isWebsite () {
      return this.form.type === 1
    },
    isApplets () {
      return this.form.type === 2
    },
    isApplication () {
      return this.form.type === 3
    }
  },
  methods: {
    handleClose (tag) {
      this.form.keywords.splice(this.form.keywords.indexOf(tag), 1)
    },
    showInput () {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm () {
      if (this.inputValue) {
        this.form.keywords.push(this.inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    async filterTopic (data) {
      let form = {}
      for (let [key, value] of Object.entries(this.formDefault)) {
        form[key] = data[key] || value
      }
      form.image = (form.image && form.image.url) ? [form.image] : []
      form.code = (form.code && form.code.url) ? [form.code] : []
      form.start_time = data.start_time ? data.start_time * 1000 : ''
      form.end_time = data.end_time ? data.end_time * 1000 : ''
      return form
    },
    async onFormSubmit () {
      await this.$refs.form.validate()
      let image = {}
      if (this.form.image.length) {
        const { image: [{ id, url }] } = this.form
        image = { id, url }
      }

      let code = {}
      if (this.form.code.length) {
        const { code: [{ id, url }] } = this.form
        code = { id, url }
      }
      const params = { ...this.form, image, code }
      params.start_time /= 1000;
      params.end_time /= 1000;
      if (this.id === 'add') {
        await store(params)
      } else {
        await edit(this.id, params)
      }
      this.$message.success('保存成功')
      this.$router.back()
    }
  }
}
</script>
